package com.faintlight.service.impl;

import com.faintlight.model.Affirmation;
import com.faintlight.model.User;
import com.faintlight.repository.AffirmationRepository;
import com.faintlight.repository.UserRepository;
import com.faintlight.service.AffirmationService;
import com.faintlight.exception.WarmException;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
public class AffirmationServiceImpl implements AffirmationService {

    private static final Logger logger = LoggerFactory.getLogger(AffirmationServiceImpl.class);
    private final AffirmationRepository affirmationRepository;
    private final UserRepository userRepository;

    @Override
    @Transactional
    public Affirmation saveAffirmation(Affirmation affirmation) {
        logger.info("📌 保存肯定语: 内容长度={}", affirmation.getContent().length());

        User user = userRepository.findById(affirmation.getUser().getId())
                .orElseThrow(() -> new WarmException("用户不存在"));
        affirmation.setUser(user);

        Affirmation saved = affirmationRepository.save(affirmation);
        logger.info("✅ 肯定语保存成功, ID={}", saved.getId());
        return saved;
    }

    @Override
    public List<Affirmation> getUserAffirmations(Long userId) {
        logger.info("🔍 查询用户 {} 的肯定语", userId);
        List<Affirmation> affirmations = affirmationRepository.findByUser_Id(userId);
        logger.info("✅ 查询成功, 共 {} 条记录", affirmations.size());
        return affirmations;
    }

    @Override
    @Transactional
    public void deleteAffirmation(Long id, Long userId) {
        Affirmation affirmation = affirmationRepository.findById(id)
                .orElseThrow(() -> new WarmException("未找到肯定语"));
        if (!affirmation.getUser().getId().equals(userId)) {
            throw new WarmException("没有权限删除这条肯定语");
        }
        affirmationRepository.delete(affirmation);
        logger.info("✅ 肯定语删除成功, ID={}", id);
    }
}